package com.mazaiting.manager.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mazaiting.auth.constant.AuthConstant;
import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.ex.exceptions.BaseException;
import com.mazaiting.common.core.ex.exceptions.BusinessException;
import com.mazaiting.common.core.ex.exceptions.EmptyObjectException;
import com.mazaiting.web.utils.UserUtil;
import com.mazaiting.manager.domain.entity.SysRole;
import com.mazaiting.manager.domain.entity.SysUserRole;
import com.mazaiting.manager.mapper.ISysRoleMapper;
import com.mazaiting.manager.mapper.ISysUserRoleMapper;
import com.mazaiting.manager.service.ISysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * sys_user_role 服务实现类
 *
 * @author 党海亮
 * @since 2022-03-29
 */
@Service
@RequiredArgsConstructor
public class SysUserRoleServiceImpl extends ServiceImpl<ISysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    private final ISysRoleMapper sysRoleMapper;

    @Override
    public boolean saveUserRoles(Long userId, List<Long> roleIds) throws BaseException {
        if (Objects.isNull(userId)) {
            return false;
        }
        // 校验是否有管理员权限
        checkRoot(userId, roleIds);
        // 根据用户 ID 删除全部关系
        boolean result = deleteByUserId(userId);
        // 3. 遍历列表插入用户 ID 与角色 ID 关系
        if (CollectionUtil.isNotEmpty(roleIds)) {
            // 根据 ID 列表查询角色关系
            Long count = sysRoleMapper.selectCount(new LambdaQueryWrapper<SysRole>().in(SysRole::getId, roleIds));
            // 判断 ID 是否都符合
            if (!(roleIds.size() == count)) {
                throw new EmptyObjectException(ResultCode.USER_ADD_ERROR_ROLE);
            }
            // 插入角色与用户关系
            result = saveBatch(roleIds.stream().map(roleId -> new SysUserRole(userId, roleId)).toList());
        } else {
            log.warn("角色 ID 列表为空");
        }
        return result;
    }

    /**
     * 校验管理员
     *
     * @param userId      用户 ID
     * @param roleIds     角色 ID 列表
     */
    private void checkRoot(Long userId, List<Long> roleIds) throws BaseException {
        // 被修改的用户如果是管理员
        if (AuthConstant.AUTH_ROOT_ID.equals(userId)) {
            // 只有管理员可以修改管理员的权限
            if (!AuthConstant.AUTH_ROOT_ID.equals(UserUtil.getUserId())) {
                throw new BusinessException(ResultCode.PERMISSION_NOT_MODIFY_ROOT);
            }
            // 角色列表一定要包含超级管理员角色
            if (!roleIds.contains(AuthConstant.AUTH_ROLE_ID)) {
                throw new BusinessException(ResultCode.ROLE_ROOT_NOT_ROOT);
            }
        }
    }

    @Override
    public boolean deleteByUserId(Long userId) {
        boolean flag = false;
        // 根据用户 ID 查询角色关系 ID
        List<SysUserRole> sysUserRoles = lambdaQuery().eq(SysUserRole::getUserId, userId).list();
        if (CollectionUtil.isNotEmpty(sysUserRoles)) {
            flag = baseMapper.deleteBatchIds(sysUserRoles) > 0;
        }
        return flag;
    }

    @Override
    public boolean deleteByUserIds(List<Long> userIdList) {
        boolean flag = false;
        // 根据用户 ID 查询角色关系 ID
        List<SysUserRole> sysUserRoles = lambdaQuery().in(SysUserRole::getUserId, userIdList).list();
        if (CollectionUtil.isNotEmpty(sysUserRoles)) {
            flag = baseMapper.deleteBatchIds(sysUserRoles) > 0;
        }
        return flag;
    }
}
